package com.taxi.driver.module.main.home;

import android.content.Context;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.qianxx.adapter.SuperAdapter;
import com.qianxx.adapter.internal.SuperViewHolder;
import com.taxi.driver.R;
import com.taxi.driver.module.vo.MessageVO;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

/**
 * 功能描述：
 */
public class HomeAdapter extends SuperAdapter<MessageVO> {

    private SimpleDateFormat sdf;

    public HomeAdapter(Context context) {
        super(context, new ArrayList<>(), R.layout.item_home_list);
        sdf = new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA);
    }

    @Override
    public void onBind(SuperViewHolder holder, int viewType, int position, MessageVO item) {
        if (item.type == 1) {
            holder.setBackgroundResource(R.id.img_message, R.drawable.home_icon_message);
            holder.setText(R.id.tv_type, "系统消息");
            if (item.sendType == 1) {
                holder.setText(R.id.tv_content, item.content);
            } else {
                holder.setText(R.id.tv_content, item.title);
            }
        } else if (item.type == 3) {
            holder.setBackgroundResource(R.id.img_message, R.drawable.home_icon_pay);
            holder.setText(R.id.tv_type, item.title);
            holder.setText(R.id.tv_content, item.content);
        }
        holder.setText(R.id.tv_time, sdf.format(new Date(item.sendTime)));

        TextView tvContent = holder.getView(R.id.tv_content);
        setLines(tvContent);
    }

    private void setLines(final TextView tv) {
        ViewTreeObserver observer = tv.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                ViewTreeObserver obs = tv.getViewTreeObserver();
                obs.removeGlobalOnLayoutListener(this);
                if (tv.getLineCount() > 2) {
                    int lineEndIndex = tv.getLayout().getLineEnd(1);
                    String text = tv.getText().toString().substring(0, lineEndIndex - 3) + "...";
                    tv.setText(text);
                }
            }
        });
    }
}
